<script setup>
	import { computed, defineProps, ref, watch, watchEffect } from 'vue'
	import { message } from 'ant-design-vue'
	import { useCustomQueryStore } from '@/views/plugin/dashboard/store/customQuery'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import { CHART_TYPES, generateChartTemplate, PROMPT_CATEGORIES } from '../templates/chartTemplates'

	const store = useCustomQueryStore()
	const props = defineProps({
		dataConnectorId: {
			type: String,
			required: true
		},
		sql: {
			type: String,
			required: true
		},
		params: {
			type: Array,
			default: () => []
		},
		xField: {
			type: String,
			default: ''
		},
		yField: {
			type: String,
			default: ''
		},
		seriesField: {
			type: String,
			default: ''
		}
	})

	// 用户自定义需求
	const customRequirement = ref('')
	// 表的元数据信息
	const tableMetadata = ref([])
	// 当前选中的图表类型
	const selectedChartType = ref('ranking')
	// 当前选中的分类
	const selectedCategory = ref('analysis')
	// 元数据缓存
	const metadataCache = ref({})
	// 数据表列表
	const tableList = ref([])
	// 支持的公式列表
	const supportedFormulas = ref({})
	// 自定义模板列表
	const customTemplates = ref([])
	// 模板预览模式
	const previewMode = ref('template') // 'template' | 'sql'

	// 计算属性：当前分类的图表类型
	const currentCategoryChartTypes = computed(() => {
		return CHART_TYPES[selectedCategory.value] || []
	})

	// 计算属性：所有图表类型（用于兼容性）
	const allChartTypes = computed(() => {
		const types = []
		Object.values(CHART_TYPES).forEach((categoryTypes) => {
			types.push(...categoryTypes)
		})
		return types
	})

	// 加载数据表列表
	const loadTables = async () => {
		try {
			tableList.value = await dataConnectorApi.tables({ id: props.dataConnectorId })
		} catch (error) {
			console.error('获取数据表列表失败:', error)
			message.error('获取数据表列表失败')
		}
	}

	// 加载支持的公式列表
	const loadSupportedFormulas = async () => {
		try {
			const result = await datasetApi.getSupportedFormulas()
			supportedFormulas.value = result
		} catch (error) {
			console.error('获取支持的公式列表失败:', error)
			message.error('获取支持的公式列表失败')
		}
	}

	// 监听数据连接器ID变化
	watch(
		() => props.dataConnectorId,
		(newId) => {
			if (newId) {
				loadTables()
				loadSupportedFormulas()
			}
		},
		{ immediate: true }
	)

	// 监听分类变化，重置图表类型选择
	watch(selectedCategory, (newCategory) => {
		const categoryTypes = CHART_TYPES[newCategory] || []
		if (categoryTypes.length > 0) {
			selectedChartType.value = categoryTypes[0].value
		}
	})

	// 获取表的元数据信息
	const loadTableMetadata = async () => {
		try {
			// 从store中获取选中的表
			const selectedTables = store.formData.config.selectedTables
			if (!selectedTables || selectedTables.length === 0) {
				return
			}

			// 清空现有元数据
			tableMetadata.value = []

			// 获取每个表的元数据
			for (const tableName of selectedTables) {
				// 检查缓存中是否存在该表的元数据
				if (!metadataCache.value[tableName]) {
					const res = await dataConnectorApi.metadata({
						id: props.dataConnectorId,
						tableName: tableName
					})
					// 将元数据添加到缓存中
					metadataCache.value[tableName] = res.columns.map((column) => ({
						...column,
						name: `${tableName}.${column.name}`,
						tableName: tableName
					}))
				}
				// 从缓存中获取元数据并添加到当前元数据列表
				tableMetadata.value.push(...metadataCache.value[tableName])
			}
		} catch (error) {
			console.error('获取表元数据失败:', error)
			message.error('获取表元数据失败')
		}
	}

	// 处理表格选择变化
	const handleTableChange = (selectedTables) => {
		store.updateSelectedTables(selectedTables)
		loadTableMetadata()
	}

	// 监听SQL变化，重新加载元数据
	watchEffect(() => {
		if (props.sql) {
			loadTableMetadata()
		}
	})

	// 生成模板
	const generateTemplate = () => {
		const template = generateChartTemplate(selectedChartType.value, {
			sql: props.sql,
			tableMetadata: tableMetadata.value,
			xField: props.xField,
			yField: props.yField,
			seriesField: props.seriesField
		})

		// 添加公式说明
		const formulaInfo =
			Object.keys(supportedFormulas.value).length > 0
				? `\n\n**可用的动态公式：**\n${Object.entries(supportedFormulas.value)
						.map(([key, desc]) => `- \${${key}} : ${desc}`)
						.join('\n')}\n`
				: ''

		return (
			template +
			formulaInfo +
			(customRequirement.value
				? `\n\n**额外需求：**\n${customRequirement.value}\n\n**输出要求：**\n只生成SQL语句，不要包含注释和其他内容。`
				: '')
		)
	}

	// 生成纯SQL模板（用于预览）
	const generateSqlTemplate = () => {
		// 这里可以实现一个简化的SQL生成逻辑
		const baseSQL = props.sql || 'SELECT * FROM your_table'
		return `-- 基于当前配置生成的SQL示例\n${baseSQL}\nWHERE DELETE_FLAG = 'NOT_DELETE'\n  AND create_time >= \${current_date} - INTERVAL 30 DAY\nORDER BY create_time DESC\nLIMIT 100`
	}

	// 复制到剪贴板
	const copyTemplate = async () => {
		const template = previewMode.value === 'template' ? generateTemplate() : generateSqlTemplate()
		try {
			await navigator.clipboard.writeText(template)
			message.success('模板已复制到剪贴板')
		} catch (err) {
			message.error('复制失败，请手动复制')
		}
	}

	// 保存自定义模板
	const saveCustomTemplate = () => {
		const template = {
			id: Date.now(),
			name: `自定义模板_${selectedChartType.value}_${new Date().toLocaleString()}`,
			category: selectedCategory.value,
			chartType: selectedChartType.value,
			content: generateTemplate(),
			createTime: new Date().toISOString()
		}

		customTemplates.value.push(template)
		// 这里可以添加持久化存储逻辑
		localStorage.setItem('dashboard_custom_templates', JSON.stringify(customTemplates.value))
		message.success('自定义模板已保存')
	}

	// 加载自定义模板
	const loadCustomTemplates = () => {
		try {
			const saved = localStorage.getItem('dashboard_custom_templates')
			if (saved) {
				customTemplates.value = JSON.parse(saved)
			}
		} catch (error) {
			console.error('加载自定义模板失败:', error)
		}
	}

	// 应用自定义模板
	const applyCustomTemplate = (template) => {
		selectedCategory.value = template.category
		selectedChartType.value = template.chartType
		// 可以进一步解析模板内容来设置其他参数
		message.success('已应用自定义模板')
	}

	// 插入公式到自定义需求中
	const insertFormula = (formulaKey) => {
		const formula = `\${${formulaKey}}`
		if (customRequirement.value) {
			customRequirement.value += ` ${formula}`
		} else {
			customRequirement.value = `请在SQL中使用 ${formula} 公式`
		}
		message.success(`已插入公式: ${formula}`)
	}

	// 初始化
	loadCustomTemplates()
</script>

<template>
	<div class="prompt-template">
		<!-- 数据表选择器 -->
		<div class="table-selector">
			<a-select
				v-model:value="store.formData.config.selectedTables"
				mode="multiple"
				style="width: 100%"
				placeholder="请选择数据表"
				@change="handleTableChange"
			>
				<a-select-option v-for="table in tableList" :key="table" :value="table">
					{{ table }}
				</a-select-option>
			</a-select>
		</div>

		<!-- 分类导航 -->
		<div class="category-selector">
			<a-tabs v-model:activeKey="selectedCategory" type="card">
				<a-tab-pane v-for="category in PROMPT_CATEGORIES" :key="category.key" :tab="category.label">
					<template #tab>
						<span> {{ category.icon }} {{ category.label }} </span>
					</template>
					<div class="category-description">
						{{ category.description }}
					</div>
				</a-tab-pane>
			</a-tabs>
		</div>

		<!-- 图表类型选择器 -->
		<div class="chart-type-selector">
			<a-radio-group v-model:value="selectedChartType">
				<a-radio-button v-for="type in currentCategoryChartTypes" :key="type.value" :value="type.value">
					{{ type.label }}
					<a-tooltip>
						<template #title>{{ type.description }}</template>
						<info-circle-outlined class="info-icon" />
					</a-tooltip>
				</a-radio-button>
			</a-radio-group>
		</div>

		<!-- 预览模式切换 -->
		<div class="preview-mode-selector">
			<a-radio-group v-model:value="previewMode" button-style="solid" size="small">
				<a-radio-button value="template">AI提示词</a-radio-button>
				<a-radio-button value="sql">SQL示例</a-radio-button>
			</a-radio-group>
		</div>

		<!-- 自定义需求 -->
		<div class="custom-requirement">
			<a-textarea
				v-model:value="customRequirement"
				placeholder="请输入额外的图表需求（可选），例如：希望图表显示百分比、添加特定的标签等"
				:auto-size="{ minRows: 3, maxRows: 5 }"
			/>
		</div>

		<!-- 公式助手 -->
		<div v-if="Object.keys(supportedFormulas).length > 0" class="formula-helper">
			<a-collapse size="small">
				<a-collapse-panel key="formulas" header="📝 可用公式参考">
					<div class="formula-list">
						<a-tag
							v-for="(desc, key) in supportedFormulas"
							:key="key"
							color="blue"
							style="margin: 2px; cursor: pointer"
							@click="insertFormula(key)"
						>
							${{ '{' + key + '}' }} - {{ desc }}
						</a-tag>
					</div>
				</a-collapse-panel>
			</a-collapse>
		</div>

		<!-- 模板预览 -->
		<div class="template-preview">
			<div class="preview-header">
				<span class="preview-title">
					{{ previewMode === 'template' ? 'AI提示词预览' : 'SQL示例预览' }}
				</span>
				<a-button-group size="small">
					<a-button @click="copyTemplate">
						<copy-outlined />
						复制
					</a-button>
					<a-button @click="saveCustomTemplate">
						<save-outlined />
						保存模板
					</a-button>
				</a-button-group>
			</div>
			<div class="preview-content">
				<pre>{{ previewMode === 'template' ? generateTemplate() : generateSqlTemplate() }}</pre>
			</div>
		</div>

		<!-- 自定义模板管理 -->
		<div v-if="customTemplates.length > 0" class="custom-templates">
			<a-collapse size="small">
				<a-collapse-panel key="templates" header="📚 我的模板">
					<div class="template-list">
						<div
							v-for="template in customTemplates"
							:key="template.id"
							class="template-item"
							@click="applyCustomTemplate(template)"
						>
							<div class="template-name">{{ template.name }}</div>
							<div class="template-meta">
								{{ template.category }} - {{ template.chartType }} -
								{{ new Date(template.createTime).toLocaleString() }}
							</div>
						</div>
					</div>
				</a-collapse-panel>
			</a-collapse>
		</div>
	</div>
</template>

<style scoped>
	.prompt-template {
		padding: 16px;
		background: #fff;
		border-radius: 2px;
	}

	.table-selector {
		margin-bottom: 16px;
	}

	.category-selector {
		margin-bottom: 16px;
	}

	.category-description {
		padding: 8px 0;
		color: rgba(0, 0, 0, 0.65);
		font-size: 14px;
		border-bottom: 1px solid #f0f0f0;
		margin-bottom: 12px;
	}

	.chart-type-selector {
		margin-bottom: 16px;
	}

	.info-icon {
		margin-left: 4px;
		font-size: 14px;
		color: rgba(0, 0, 0, 0.45);
	}

	.preview-mode-selector {
		margin-bottom: 16px;
		text-align: right;
	}

	.custom-requirement {
		margin-bottom: 16px;
	}

	.formula-helper {
		margin-bottom: 16px;
	}

	.formula-list {
		max-height: 200px;
		overflow-y: auto;
	}

	.template-preview {
		margin-bottom: 16px;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		overflow: hidden;
	}

	.preview-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 16px;
		background: #fafafa;
		border-bottom: 1px solid #d9d9d9;
	}

	.preview-title {
		font-weight: 500;
		color: rgba(0, 0, 0, 0.85);
	}

	.preview-content {
		background-color: #f5f5f5;
		padding: 16px;
		max-height: 400px;
		overflow-y: auto;
	}

	.preview-content pre {
		margin: 0;
		white-space: pre-wrap;
		word-wrap: break-word;
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		font-size: 13px;
		line-height: 1.5;
	}

	.custom-templates {
		margin-top: 16px;
	}

	.template-list {
		max-height: 200px;
		overflow-y: auto;
	}

	.template-item {
		padding: 8px 12px;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		margin-bottom: 8px;
		cursor: pointer;
		transition: all 0.3s;
	}

	.template-item:hover {
		border-color: #1890ff;
		background-color: #f6ffed;
	}

	.template-name {
		font-weight: 500;
		color: rgba(0, 0, 0, 0.85);
		margin-bottom: 4px;
	}

	.template-meta {
		font-size: 12px;
		color: rgba(0, 0, 0, 0.45);
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.prompt-template {
			padding: 12px;
		}

		.preview-header {
			flex-direction: column;
			gap: 8px;
			align-items: flex-start;
		}

		.chart-type-selector .ant-radio-group {
			display: flex;
			flex-wrap: wrap;
			gap: 4px;
		}
	}

	/* 深色主题适配 */
	@media (prefers-color-scheme: dark) {
		.prompt-template {
			background: #1f1f1f;
		}

		.preview-content {
			background-color: #2d2d2d;
			color: #e6e6e6;
		}

		.template-item {
			border-color: #434343;
			background-color: #262626;
		}

		.template-item:hover {
			border-color: #1890ff;
			background-color: #111b26;
		}
	}
</style>
